package com.ctsi.ssdc.admin.service.impl;


import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ctsi.ssdc.admin.domain.CscpRoleMenuExample;
import com.ctsi.ssdc.admin.domain.CscpRoles;
import com.ctsi.ssdc.admin.domain.CscpRolesExample;
import com.ctsi.ssdc.admin.domain.CscpRolesExample.Criteria;
import com.ctsi.ssdc.admin.domain.CscpUserRoleExample;
import com.ctsi.ssdc.admin.domain.dto.CscpRolesCriteria;
import com.ctsi.ssdc.admin.domain.dto.CscpRolesDTO;
import com.ctsi.ssdc.admin.repository.CscpRoleMenuRepository;
import com.ctsi.ssdc.admin.repository.CscpRolesRepository;
import com.ctsi.ssdc.admin.repository.CscpUserRoleRepository;
import com.ctsi.ssdc.admin.service.CscpRolesService;
import com.ctsi.ssdc.admin.service.mapper.CscpRolesMapper;
import com.ctsi.ssdc.model.PageResult;
import com.github.pagehelper.PageHelper;

/**
 * Service Implementation for managing CscpRoles.
 *
 * @author ctsi biyi generator
 *
 */
@Service
public class CscpRolesServiceImpl implements CscpRolesService {

    private final Logger log = LoggerFactory.getLogger(CscpRolesServiceImpl.class);

    @Autowired
    private CscpRolesRepository cscpRolesRepository;

    private final CscpRolesMapper cscpRolesMapper;
    
    @Autowired
    private CscpUserRoleRepository cscpUserRoleRepository;
    
    
    @Autowired
    private CscpRoleMenuRepository roleMenuRepository;

    public CscpRolesServiceImpl(CscpRolesMapper cscpRolesMapper) {
        this.cscpRolesMapper = cscpRolesMapper;
    }

    /**
     * insert a cscpRoles.
     *
     * @param cscpRolesDTO the entity to insert
     * @return the persisted entity
     */
    @Override
    public CscpRolesDTO insert(CscpRolesDTO cscpRolesDTO) {
        log.debug("Request to insert CscpRoles : {}", cscpRolesDTO);
        
        CscpRoles cscpRoles = cscpRolesMapper.toEntity(cscpRolesDTO);
        cscpRolesRepository.insert(cscpRoles);
        return cscpRolesMapper.toDto(cscpRoles);
    }
    
     /**
     * update a cscpRoles.
     *
     * @param cscpRolesDTO the entity to update
     * @return the persisted entity
     */
    @Override
    public CscpRolesDTO update(CscpRolesDTO cscpRolesDTO) {
        log.debug("Request to update CscpRoles : {}", cscpRolesDTO);
        
        CscpRoles cscpRoles = cscpRolesMapper.toEntity(cscpRolesDTO);
        cscpRolesRepository.updateByPrimaryKeySelective(cscpRoles);
        return cscpRolesMapper.toDto(cscpRoles);
    }
    
    

    /**
     * Get all the cscpRoless.
     *
     * @return the list of entities
     */
    @Override
    @Transactional(readOnly = true)
    public PageResult<CscpRolesDTO> findAll() {
        log.debug("Request to get all CscpRoless");
        
        List<CscpRolesDTO> data = cscpRolesRepository.selectByExample(null).stream()
                .map(cscpRolesMapper::toDto)
                .collect(Collectors.toCollection(LinkedList::new));
                
        long count = 0L;
		
		if(CollectionUtils.isNotEmpty(data)) {
			count = cscpRolesRepository.countByExample(null);
		}
		
		return new PageResult<CscpRolesDTO>(data,count,count);        
        
    }

    /**
     * Get one cscpRoles.
     *
     * @param id the id of the entity
     * @return the entity
     */
    @Override
    @Transactional(readOnly = true)
    public CscpRolesDTO findOne(Integer id) {
        log.debug("Request to get CscpRoles : {} ", id);
        
        CscpRoles cscpRoles = cscpRolesRepository.selectByPrimaryKey(id);
        return cscpRolesMapper.toDto(cscpRoles);
    }

    /**
     * Delete the cscpRoles .
     *
     * @param id the id of the entity
     */
    @Override
    @Transactional
    public void delete(Integer id) {
        log.debug("Request to delete CscpRoles : {} ", id);
        
        cscpRolesRepository.deleteByPrimaryKey(id);
        
      //删除用户与角色关联表；
        CscpUserRoleExample example4 = new CscpUserRoleExample();
        CscpUserRoleExample.Criteria cx4 = example4.createCriteria();
        cx4.andRoleIdEqualTo(id);
        cscpUserRoleRepository.deleteByExample(example4);
        
      //角色和菜单关联表；
        CscpRoleMenuExample rm = new CscpRoleMenuExample();
        CscpRoleMenuExample.Criteria cx = rm.createCriteria();
        cx.andRoleIdEqualTo(id);
        roleMenuRepository.deleteByExample(rm);
    }
    
    private String getPageOrderBy(Pageable page) {
		
		if(page!= null && page.getSort() != null) {
			
			StringBuilder sb = new StringBuilder();
			
			page.getSort().forEach(sort -> sb.append(sort.getProperty())
					.append(" ").append(sort.getDirection()).append(","));
			
			if(sb.length() > 1) {
				return (sb.substring(0,sb.length()-1));
			}
		}
		
		return null;
	}
	
	/**
     * Get the cscpRoless.
     *
     * @return the list of entities
     */
    @Override
    @Transactional(readOnly = true)
    public PageResult<CscpRolesDTO> findByCscpRolesDTO(CscpRolesDTO cscpRolesDTO, Pageable page) {
    
        log.debug("Request to find CscpRoless");
        
    	CscpRolesExample example = new CscpRolesExample();
    	
    	example.setPage(page);
		
		Criteria critieria = example.createCriteria();
		
		if(cscpRolesDTO.getId() != null) {
			critieria.andIdEqualTo(cscpRolesDTO.getId());
		}		
		if(cscpRolesDTO.getParentId() != null) {
			critieria.andParentIdEqualTo(cscpRolesDTO.getParentId());
		}		

		if(StringUtils.isNotBlank(cscpRolesDTO.getName())) {
			critieria.andNameLike(String.format("%%%s%%", cscpRolesDTO.getName()));
		}		
		if(StringUtils.isNotBlank(cscpRolesDTO.getRoleExtent())) {
			critieria.andRoleExtentLike(String.format("%%%s%%", cscpRolesDTO.getRoleExtent()));
		}		
		if(StringUtils.isNotBlank(cscpRolesDTO.getIcon())) {
			critieria.andIconLike(String.format("%%%s%%", cscpRolesDTO.getIcon()));
		}		
		
		String orderBy = getPageOrderBy(page);

		if(StringUtils.isNotEmpty(orderBy)) {
			example.setOrderByClause(orderBy);
		}
		PageHelper.startPage(page.getPageNumber(), page.getPageSize());
		List<CscpRolesDTO> data = cscpRolesMapper.toDto(cscpRolesRepository.selectByExamplewithPage(example));
    
     	long count = 0L;
		
		if(CollectionUtils.isNotEmpty(data)) {
			count = cscpRolesRepository.countByExample(example);
		}
		
		return new PageResult<CscpRolesDTO>(data,count,count);       
		
    }
    
    /**
     * Get the cscpRoless.
     *
     * @param cscpRolesCriteria
     * @param page
     * @return
     */
	public PageResult<CscpRolesDTO> findByCscpRolesCriteria(CscpRolesCriteria cscpRolesCriteria, Pageable page) {
	
		CscpRolesExample example = new CscpRolesExample();
    	
    	example.setPage(page);
		
		Criteria criteria = example.createCriteria();
		
		if(cscpRolesCriteria != null) {
			cscpRolesCriteria.buildCriteria(criteria);
		}		

		String orderBy = getPageOrderBy(page);

		if(StringUtils.isNotEmpty(orderBy)) {
			example.setOrderByClause(orderBy);
		}
		PageHelper.startPage(page.getPageNumber(), page.getPageSize());
		List<CscpRolesDTO> data = cscpRolesMapper.toDto(cscpRolesRepository.selectByExamplewithPage(example));
		
		long count = 0L;
		
		if(CollectionUtils.isNotEmpty(data)) {
			count = cscpRolesRepository.countByExample(example);
		}
		
		return new PageResult<CscpRolesDTO>(data,count,count);    
		
	}
    
    
}
